import React, { forwardRef, useImperativeHandle } from 'react';
import { Link } from 'react-router-dom';
import { Table, Space, Button, Modal, message } from 'antd';
import { Authorized } from '@/components';
import permission from '@/config/permission';
import enums from '@/enums';
import { useHistory } from 'react-router-dom';
import { useTaskList, useDownloadResourceFile, useDeleteTask } from './hooks';

/**
 * 导入任务列表
 */
function TaskList (props, ref) {
  const { form } = props;

  const [{ confirm }, contextHolder] = Modal.useModal();
  const history = useHistory();
  const taskList = useTaskList({ form });

  const downloadResourceFile = useDownloadResourceFile({
    onSuccess () {
      message.success('下载成功');
    },
    onError (err) {
      message.error('下载失败');
    },
  });

  const deleteTask = useDeleteTask({
    onSuccess () {
      taskList.refresh();
      message.success('删除成功');
    },
    onError () {
      message.error('删除失败');
    },
  });

  useImperativeHandle(ref, () => taskList);

  return (
    <>
      <Table
        rowKey="ossFileUploadTaskId"
        scroll={{ x: 'max-content' }}
        columns={[
          {
            title: '模版名称',
            dataIndex: 'ossFileUploadTaskName',
            render (text, record) {
              return (
                <>
                  <Link to={{ pathname: '/resource/import-tasks/detail', state: record }}>
                    {text}
                  </Link>
                  <div>{record.ossFileUploadTaskId}</div>
                </>
              );
            },
          },
          {
            title: '模版ID',
            dataIndex: 'temid',
          },
          {
            title: '模版描述',
            dataIndex: 'objectStoragedes',
          },
          {
            title: '创建人',
            dataIndex: 'author',
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
          },
          {
            title: '更新人',
            dataIndex: 'author',
            render: (text) => text ?? '-',
          },
          {
            title: '更新时间',
            dataIndex: 'updataTime',
          },
          {
            title: '操作',
            render ({ temid, status, ossFileUploadTaskName }) {
              return (
                <Space size="middle">
                  <Authorized authority={permission.resourceImportTasks_edit} noMatch={null}>
                    <Button
                      style={{ padding: 0 }}
                      type="link"
                      onClick={() => {
                        const currentTask = [
                          // { ossFileUploadTaskName: '服务器配置模版', temid: 'TPL_20231001', objectStoragedes: '用于新服务器初始化配置的标准模版', author: '张三', createTime: '2023-10-01 09:30:00', updataTime: '2023-10-01 15:45:00', status: 'upload-success' },
                          // { ossFileUploadTaskName: '数据库备份模版', temid: 'TPL_20231002', objectStoragedes: '每日自动备份数据库的任务模版', author: '李四', createTime: '2023-10-02 10:15:00', updataTime: '2023-10-02 16:20:00', status: 'check-success' },
                          // { ossFileUploadTaskName: '日志清理模版', temid: 'TPL_20231003', objectStoragedes: '定期清理系统日志的维护模版', author: '王五', createTime: '2023-10-03 11:20:00', updataTime: '2023-10-03 14:10:00', status: 'upload-fail' },
                          ...JSON.parse(localStorage.getItem('tasks') || '[]')
                        ].find(item => item.temid === temid);
                        // const currentTask = taskList.tableProps.dataSource.find(item => item.temid === temid);
                        console.log(currentTask, 222222222222222222222222222222222222);
                        // history.push(`/template/update?temid=${temid}`);
                        history.push({
                          pathname: '/template/cloudUpdate',
                          state: { task: currentTask, isEdit: true }
                        });
                      }}
                    >
                      编辑
                    </Button>
                  </Authorized>
                  <Authorized authority={permission.resourceImportTasks_delete} noMatch={null}>
                    <Button
                      style={{ padding: 0 }}
                      type="link"

                      onClick={() => {


                      }}
                    >
                      克隆
                    </Button>
                  </Authorized>
                  <Authorized authority={permission.resourceImportTasks_delete} noMatch={null}>
                    <Button
                      style={{ padding: 0 }}
                      type="link"
                      disabled={!['upload-fail', 'check-success', 'check-fail'].includes(status)}
                      onClick={() => {

                        confirm({
                          title: '删除导入任务',
                          content: `确认删除导入任务“${ossFileUploadTaskName}”？`,
                          onOk () {
                            return deleteTask.runAsync(temid);
                          },
                        });
                      }}
                    >
                      删除
                    </Button>
                  </Authorized>
                </Space>
              );
            },
          },
        ]}
        {...taskList.tableProps}
        dataSource={[

          ...JSON.parse(localStorage.getItem('tasks') || '[]'),

        ]}
        pagination={{
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
          ...taskList.tableProps.pagination,
        }}
      />
      {contextHolder}
    </>
  );
}

export default forwardRef(TaskList);
